package spring.boot.zk.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class ZookeeperConfig {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private static CuratorFramework client = null ;

    @Value("${apache.zookeeper.connect-url}")
    private String connectUrl;
    @Value("${apache.zookeeper.connection-timeout}")
    private Integer connectionTimeout;
    @Value("${apache.zookeeper.session-timeout}")
    private Integer sessionTimeout;

    @Value("${apache.zookeeper.retrypolicy.base-sleep-time}")
    private Integer baseSleepTime;
    @Value("${apache.zookeeper.retrypolicy.max-retries}")
    private Integer maxRetries;

    /**
     * 初始化
     */
    @PostConstruct
    public void init (){
        logger.info("zooKeeper client init...");
        //当zk连接时失败的重连策略
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseSleepTime, maxRetries);

        //获得实例对象，拿到ZK client
        client = CuratorFrameworkFactory.newClient(
                connectUrl,
                sessionTimeout,
                connectionTimeout,
                retryPolicy);

        //安全认证
           /* List<AuthInfo> authInfos = new ArrayList<>();
            authInfos.add(new AuthInfo(zookeeperConfig.getScheme(), zookeeperConfig.getAuthId().getBytes()));
            client = CuratorFrameworkFactory.builder()
                    .authorization(authInfos)
                    .connectString(zookeeperConfig.getConnectUrl())
                    .sessionTimeoutMs(zookeeperConfig.getSessionTimeout())
                    .connectionTimeoutMs(zookeeperConfig.getConnectionTimeout())
                    .retryPolicy(retryPolicy)
                    .namespace("workspace")
                    .build();*/
        client.start();
        logger.info("zooKeeper client start...");

    }
    public static CuratorFramework getClient (){
        return client ;
    }
    public static void closeClient (){
        if (client != null){
            client.close();
        }
    }
}